<?php

namespace caroltc\jenkinsapp\controller;
use caroltc\jenkinsapp\library\UserSession;
use caroltc\jenkinsapp\util\Log;
use caroltc\jenkinsapp\util\RequestTool;

/**
 * Created by PhpStorm.
 * User: root
 * Date: 11/14/18
 * Time: 11:27 AM
 */
class BaseController
{
    use RequestTool;

    protected $user_id;
    protected $username;
    protected $is_admin;

    public function __construct()
    {
        // 记录访问日志
        Log::i('[new request] data:' . json_encode($this->getAllRequestParams()));
    }

    /**
     * 检查并获取用户session
     * @return null
     */
    protected function checkUserSession()
    {
        $this->checkParams(['token']);
        $UserSession = new UserSession();
        $user = $UserSession->findUserByToken($this->getRequestParam('token'));
        if (false === $user) {
            return $this->responseFail(40000, $UserSession->error);
        }
        if (empty($user)) {
            return $this->responseFail(40000, 'token is invalid');
        }
        $this->user_id = $user['user_id'];
        $this->username = $user['username'];
        $this->is_admin = intval($user['is_admin']) === 1;
    }

    /**
     * 检查管理员权限
     * @return null
     */
    protected function checkUserAdmin()
    {
        if (!$this->is_admin) {
            return $this->responseFail(50000, '无权限');
        }
    }
}